<script setup lang="ts">
  import { ref, watch, reactive, computed } from 'vue';
  import {
    boxDataQuery,
    boxDataUpdate,
    boxDataSetEmpty,
  } from '@/api/operation-monitoring';
  import { Notification } from '@arco-design/web-vue';

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '数量',
      dataIndex: 'itemQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '箱子号',
      dataIndex: 'workbinCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '合格证号',
      dataIndex: 'mesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '箱子表主键',
      dataIndex: 'msWorkbinMaterialId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单表主键',
      dataIndex: 'wmsDeliveryPlanId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '台账表主键',
      dataIndex: 'wmsItemInventoryId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  // 创建一个响应式的本地副本
  const localTableData = ref<any>();
  // 数据库一共有多少条
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const selectedKeys = ref<string[]>();
  const rowSelection = reactive({
    type: 'checkbox' as 'checkbox' | 'radio',
    showCheckedAll: true,
  });
  // 计算已选择的表格数据
  const selectedTableData = computed(() => {
    return localTableData.value.filter((item: any) =>
      selectedKeys.value?.includes(item.PAGEHELPER_ROW_ID)
    );
  });
  const formValues = reactive({
    itemCode: '',
    qualityCode: '',
    workbinCode: '',
    wmsItemInventoryId: '',
    wmsDeliveryPlanId: '',
  });
  const form = reactive({
    itemCode: '',
    qualityCode: '',
    itemQty: '',
    workbinCode: '',
  });
  const randomNum = ref<number>();
  const validateNum = ref<number>();
  const dataBoxModalVisible = ref<boolean>(false);
  const validateModalVisible = ref<boolean>(false);
  async function handleSearch() {
    const response = await boxDataQuery({
      queryParam: formValues,
      page: { currentPage: pageNum.value, pageSize: pageSize.value, total: 0 },
    });
    if (response) {
      localTableData.value = response.list;
      total.value = response.total;
    } else {
      Notification.warning({
        title: '提示',
        content: '查询失败',
        closable: true,
      });
    }
  }
  function reset() {
    Object.keys(formValues).forEach((key) => {
      (formValues as Record<string, any>)[key] = '';
    });
    setTimeout(() => {
      handleSearch();
    }, 150);
  }
  async function validateModalOk() {
    if (validateNum.value !== randomNum.value) {
      Notification.error({
        title: '提示',
        content: '验证失败',
        closable: true,
      });
      return;
    }
    // 验证通过后清除已选择
    selectedKeys.value = [];
    // 修改箱子数据
    if (randomNum.value && randomNum.value <= 50) {
      const response = await boxDataUpdate(form);
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: `${response.message}`,
          closable: true,
        });
        handleSearch();
      } else {
        Notification.error({
          title: '失败',
          content: `${response.message ? response.message : '修改失败'}`,
          closable: true,
        });
      }
    }
    // 设置为空箱
    if (randomNum.value && randomNum.value >= 51) {
      const response = await boxDataSetEmpty(form);
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: `${response.message}`,
          closable: true,
        });
        handleSearch();
      } else {
        Notification.error({
          title: '失败',
          content: `${response.message ? response.message : '修改失败'}`,
          closable: true,
        });
      }
    }
  }

  function modalOpen(item: number) {
    if (selectedKeys.value?.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请选择一条数据',
        closable: true,
      });
    } else {
      switch (item) {
        case 1:
          dataBoxModalVisible.value = true;
          Object.assign(form, selectedTableData.value[0]);
          break;
        case 2:
          // 51-99的随机数
          randomNum.value = Math.floor(Math.random() * (99 - 51 + 1)) + 51;
          validateNum.value = undefined;
          validateModalVisible.value = true;
          break;
        default:
      }
    }
  }
  function modalOk() {
    // 10-50的随机数
    randomNum.value = Math.floor(Math.random() * (50 - 10 + 1)) + 10;
    validateNum.value = undefined;
    validateModalVisible.value = true;
  }
  // 监听页面变化
  watch([pageNum, pageSize], () => {
    handleSearch();
  });
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
</script>

<template>
  <div class="content-page">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input
          v-model="formValues.itemCode"
          placeholder="图号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.qualityCode"
          placeholder="质量编号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.workbinCode"
          placeholder="缓存箱编号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.wmsItemInventoryId"
          placeholder="台账ID"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.wmsDeliveryPlanId"
          placeholder="交接单ID"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
    </a-row>
    <a-space style="margin-top: 16px">
      <a-button type="primary" size="large" @click="handleSearch">
        查询
      </a-button>
      <a-button size="large" @click="reset">重置</a-button>
      <a-button type="outline" size="large" @click="modalOpen(1)">
        修改箱子数据
      </a-button>
      <a-button type="outline" size="large" @click="modalOpen(2)">
        设置为空箱
      </a-button>
    </a-space>
    <a-divider />
    <div>
      <a-table
        v-model:selected-keys="selectedKeys"
        :stripe="true"
        class="top-table"
        :pagination="false"
        :columns="columns"
        :data="localTableData"
        :row-selection="rowSelection"
        row-key="PAGEHELPER_ROW_ID"
      >
      </a-table>
      <div class="page-position">
        <a-pagination
          :total="total"
          :current="pageNum"
          :page-size="pageSize"
          show-total
          show-jumper
          show-page-size
          @change="change"
          @update:page-size="changeSize"
        />
      </div>
    </div>
  </div>
  <a-modal
    v-model:visible="dataBoxModalVisible"
    @ok="modalOk"
    @cancel="() => (dataBoxModalVisible = false)"
  >
    <template #title> 缓存箱数据修改 </template>
    <a-space direction="vertical" fill>
      <a-form :model="form">
        <a-form-item field="itemCode" label="图号">
          <a-input v-model="form.itemCode"></a-input>
        </a-form-item>
        <a-form-item field="qualityCode" label="质量编号">
          <a-input v-model="form.qualityCode"></a-input>
        </a-form-item>
        <a-form-item field="startLotNo" label="数量">
          <a-input v-model="form.itemQty"></a-input>
        </a-form-item>
        <a-form-item field="endLotNo" label="箱子号">
          <a-input v-model="form.workbinCode"></a-input>
        </a-form-item>
      </a-form>
    </a-space>
  </a-modal>
  <a-modal
    v-model:visible="validateModalVisible"
    @ok="validateModalOk"
    @cancel="() => (validateModalVisible = false)"
  >
    <template #title> 验证提示 </template>
    <div style="font-size: large">
      请输入:
      <span class="validate-font">{{ randomNum }}</span>
    </div>
    <a-input-number v-model:model-value="validateNum"></a-input-number>
  </a-modal>
</template>

<style scoped>
  span {
    margin-bottom: 16px;
  }
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .content-page {
    padding-left: 12px;
    padding-right: 12px;
  }
  .validate-font {
    font-size: larger;
    font-weight: bolder;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  }
</style>
